package com.ruoyi.energy.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.energy.domain.vo.*;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ParkCarUtil {
    /**
     * 根据类型获得属性和属性值
     *
     * @param model
     * @return
     * @throws Exception
     */
    public static Map<String, Object> reflectModel(Object model) throws Exception {
        Map<String, Object> map = new HashMap<>();
        for (Field field : model.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            //  logger.info(model.getClass().getName() + "===>  " + field.getName() + ":" + field.get(model) );
            if (field.get(model) == null) {
                map.put(field.getName(), "");
            } else {
                map.put(field.getName(), field.get(model));
            }
        }
        return map;
    }

//    public static String HMACSHA256(String data, String key) throws Exception {
//
//        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
//
//        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
//
//        sha256_HMAC.init(secret_key);
//
//        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
//
//        StringBuilder sb = new StringBuilder();
//
//        for (byte item : array) {
//            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
//        }
//        return sb.toString().toUpperCase();
//    }

//    public static String doSign(String timestemp, String data) throws Exception {
//        char[] ch = timestemp.toCharArray();
//        String key = String.valueOf(ch[0]) + String.valueOf(ch[2]) + String.valueOf(ch[4])
//                + String.valueOf(ch[6]) + String.valueOf(ch[8]) + String.valueOf(ch[9]);
//        String sign = HMACSHA256(data, key);
//        return sign;
//
//    }


    public static String getTimestamp() {
        return System.currentTimeMillis() / 1000 + "";
    }


    /**
     * 添加月租车辆
     * @param parkId
     * @param plateId
     * @param beginDate
     * @param endDate
     * @param carOwnName
     * @param carOwnPhone
     * @param areaName
     * @return
     */
    public static ParkCarResponseVO addMonthCar(String parkId, String plateId,
                                                String beginDate, String endDate,
                                                String carOwnName, String carOwnPhone, String areaName) {

        try {
            ParkCarResponseVO response = addInnerCar(parkId, plateId, PlateTypeEnum.MONTH_CAR.getCarType(),
                    null, beginDate, endDate, carOwnName, carOwnPhone, areaName);
            return response;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 添加免费车辆
     * @param parkId
     * @param plateId
     * @param beginDate
     * @param endDate
     * @param carOwnName
     * @param carOwnPhone
     * @param areaName
     * @return
     */
    public static ParkCarResponseVO addFreeCar(String parkId, String plateId,
                                                String beginDate, String endDate,
                                                String carOwnName, String carOwnPhone, String areaName) {

        try {
            ParkCarResponseVO response = addInnerCar(parkId, plateId, PlateTypeEnum.FREE_CAR.getCarType(),
                    null, beginDate, endDate, carOwnName, carOwnPhone, areaName);
            return response;
        } catch (Exception e) {
            return null;
        }
    }


    public static ParkCarResponseVO addInnerCar(String parkId, String plateId,
                                                String plateType, String plateState,
                                                String beginDate, String endDate,
                                                String carOwnName, String carOwnPhone, String areaName) throws Exception {
//免费车时，非空缴费状态：
//永久免费
//固定时段免费
//每月时段免费
//其它可为空
        InnerCarRequestVO request = new InnerCarRequestVO();
        request.setPark_id(parkId);
        request.setPlate_id(plateId);
        request.setPlate_type(plateType);
        request.setPlate_state(plateState);
        request.setBegin_date(beginDate);
        request.setEnd_date(endDate);
        request.setCarown_name(carOwnName);
        request.setCarown_phone(carOwnPhone);
        request.setRecharge_amount("0");
        request.setArea_name(areaName);
        String timestamp = getTimestamp();
        request.setTimestamp(timestamp);

        Map<String, Object> fields = reflectModel(request);
        List<String> fieldList = new ArrayList<String>();
        for (Map.Entry<String, Object> entry : fields.entrySet()) {
            if (StringUtils.isNotEmpty(entry.getValue().toString())) {
                fieldList.add(entry.getValue().toString());
            }
        }
        String[] signs = fieldList.stream().toArray(String[]::new);
        request.setSignature(HMACSHA256.getSignUtil(timestamp, signs));
        String postUrl = ConstantValue.ADD_INNER_CAR + HMACSHA256.getTaskCreateJsonReq(JSONUtil.toJsonStr(request));
        String response = HttpRequest.post(postUrl).timeout(20000)
                .execute().body();
        System.out.println("response===>" + response);
        ParkCarResponseVO responseVO = JSONUtil.toBean(response, ParkCarResponseVO.class);
        return responseVO;

    }


    public static ParkPictureResponseVO getParkPicture(String parkId, String queryType, String pictureName) throws Exception {
        ParkPictureRequestVO request = new ParkPictureRequestVO();
        request.setPark_id(parkId);
        request.setQuery_type(queryType);
        request.setPlate_picturename(pictureName);
        String timestamp = getTimestamp();
        request.setTimestamp(timestamp);
        Map<String, Object> fields = reflectModel(request);
        List<String> fieldList = new ArrayList<String>();
        for (Map.Entry<String, Object> entry : fields.entrySet()) {
            if (StringUtils.isNotEmpty(entry.getValue().toString())) {
                fieldList.add(entry.getValue().toString());
            }
        }

        String[] signs = fieldList.stream().toArray(String[]::new);
        request.setSignature(HMACSHA256.getSignUtil(timestamp, signs));
        System.out.println("josn==>" + JSONUtil.toJsonStr(request));

        String postUrl = ConstantValue.GET_PARK_PICTURE + HMACSHA256.getTaskCreateJsonReq(JSONUtil.toJsonStr(request));

        System.out.println("postURL ===>" + postUrl);
        String response = HttpRequest.post(postUrl).timeout(20000)
                .execute().body();
        System.out.println("response===>" + response);
        ParkPictureResponseVO responseVO = JSONUtil.toBean(response, ParkPictureResponseVO.class);
        return responseVO;

    }


    public static ParkCarResponseVO setServiceAddress(String parkId, String serviceAddress) throws Exception {
        ParkUrlRequestVO request = new ParkUrlRequestVO();
        request.setPark_id(parkId);
        request.setUser_id(ConstantValue.USER_NAME);
        request.setUser_password(ConstantValue.PWD);
        request.setUrl_name(serviceAddress);
        String timestamp = getTimestamp();
        request.setTimestamp(timestamp);
        Map<String, Object> fields = reflectModel(request);
        List<String> fieldList = new ArrayList<String>();
        for (Map.Entry<String, Object> entry : fields.entrySet()) {
            if (StringUtils.isNotEmpty(entry.getValue().toString())) {
                fieldList.add(entry.getValue().toString());
            }
        }
        String[] signs = fieldList.stream().toArray(String[]::new);
        request.setSignature(HMACSHA256.getSignUtil(timestamp, signs));
        String postUrl = ConstantValue.SET_PARK_URL + HMACSHA256.getTaskCreateJsonReq(JSONUtil.toJsonStr(request));
        System.out.println("postURL ===>" + postUrl);
        String response = HttpRequest.post(postUrl).timeout(20000)
                .execute().body();
        System.out.println("response===>" + response);
        ParkCarResponseVO responseVO = JSONUtil.toBean(response, ParkCarResponseVO.class);
        return responseVO;
    }


    public static ParkCarResponseVO syncData() {
        InnerCarInterfaceVO innerCarInterfaceVO = new InnerCarInterfaceVO();


        Map<String, Object> param = new HashMap<>();
        param.put("data", JSONUtil.toJsonStr(innerCarInterfaceVO));
        String rs = HttpRequest.post(ConstantValue.PARK_URL).form(param).timeout(20 * 1000).execute().body();

        if (StringUtils.isNotBlank(rs)) {
            ParkCarResponseVO resultVO = JSONUtil.toBean(rs, ParkCarResponseVO.class);

            return resultVO;
        }

        return null;
    }


}
